import { Label, Node, Prefab, Sprite, SpriteFrame, Texture2D, UITransform, _decorator } from 'cc';
import { ResMgr } from '../../../Framework/Scripts/Managers/ResMgr';

import { UIComponent, UIMgr } from '../../../Framework/Scripts/Managers/UIMgr';
import { GameApp } from '../GameApp';
import { UserData } from '../userData/UserData';

const { ccclass, property } = _decorator;

@ccclass('SkillChoiceUI_UICtrl')
export class SkillChoiceUI_UICtrl extends UIComponent {
    private skills: {} = null
    private skillroot: Node = null


    private randomSkill(isOK: boolean = true) {
        if(!isOK){
            return
        }
        let randomSkills = null

        randomSkills = this.getRandomSkills();
        console.log("randomSkills:::::::", randomSkills);
        if (!randomSkills) {
            //出错了 退出页面





            UIMgr.Instance.DestroyUIView(this.node.name)
            return
        }


        console.log(randomSkills);
        const len: number = randomSkills.length;

        let nodeArr: Node[] = new Array()
        switch (len) {
            case 2:
                this.skillroot.getChildByName("1").active = false

                this.skillroot.getChildByName("2").setPosition(-200, 0, 0)
                this.skillroot.getChildByName("3").setPosition(200, 0, 0)
                nodeArr.push(this.skillroot.getChildByName("2"))
                nodeArr.push(this.skillroot.getChildByName("3"))
                break;

            case 1:
                this.skillroot.getChildByName("1").active = false

                nodeArr.push(this.skillroot.getChildByName("2"))
                this.skillroot.getChildByName("3").active = false
                break;

            default:
                nodeArr.push(this.skillroot.getChildByName("1"))
                nodeArr.push(this.skillroot.getChildByName("2"))
                nodeArr.push(this.skillroot.getChildByName("3"))
                break;
        }

        for (let i = 0; i < len; i++) {

            const n: Node = nodeArr[i];
            const obj: any = randomSkills[i];



            const okBtn = n.getChildByName("okBtn");

            // 移除之前的监听器

            okBtn.off(Node.EventType.TOUCH_END);


            okBtn.on(Node.EventType.TOUCH_END, () => {



                UserData.Instance.localData["playerConfig"][UserData.Instance.localData["playerType"]]["skill"][obj.key] += 1

                UserData.Instance.saveLocalData()
                console.log("添加技能成功", UserData.Instance.localData);

                UIMgr.Instance.DestroyUIView(this.node.name)
            }, this);

            const name: string = randomSkills[i]["key"]
            const imageAsset = ResMgr.Instance.getAsset("GUI", "skillIcon/" + name)

            const spriteFrame = new SpriteFrame();
            const texture = new Texture2D();
            texture.image = imageAsset;
            spriteFrame.texture = texture;

            n.getChildByName("head").getComponent(Sprite).spriteFrame = spriteFrame;

            // ResMgr.Instance.preloadAsset("GUI", "skillIcon/" + name + "/spriteFrame", SpriteFrame, (asset) => {

            //     n.getChildByName("head").getComponent(Sprite).spriteFrame = asset;

            // })
            n.getChildByName("name").getComponent(Label).string = obj.name;
            n.getChildByName("str").getComponent(Label).string = obj.str;
            n.getChildByName("level").getComponent(Label).string = (obj.level + 1) + "级";
        }
    }


    onLoad() {
        this.skills = GameApp.Instance.playerData["config"]


        this.skillroot = this.ViewNode("skillRoot")

        this.AddButtonListener("suijiBtn", this, () => {
            this.randomSkill()
        
            

        })


    }

    private getRandomSkills(): any[] {
        // 确保 this.skills 是一个对象，并且其中的每个值也是对象
        if (typeof this.skills !== 'object' || !this.skills) {
            console.error("Skills data is not valid", this.skills);
            return null;
        }

        const gameLevel: number = GameApp.Instance.level
        let filteredSkills = []
        //  let filteredSkills = Object.keys(this.skills).filter(key => (this.skills[key].level < this.skills[key].max) && (gameLevel >= this.skills[key].minLevel));


        for (let key in this.skills) {
            if (this.skills[key].level < this.skills[key].max && gameLevel >= this.skills[key].minLevel) {
                filteredSkills.push(key)
            }
        }

        if (filteredSkills.length <= 0) {

            return null
        }
        console.log("最终剔除的表", filteredSkills);

        // 打乱过滤后的技能列表
        for (let i = filteredSkills.length - 1; i > 0; i--) {
            let j = Math.floor(Math.random() * (i + 1));
            [filteredSkills[i], filteredSkills[j]] = [filteredSkills[j], filteredSkills[i]];
        }



        let selectedSkills = [];
        let count: number = 3//默认三个
        if (filteredSkills.length < 3) {
            //有几个显示几个
            count = filteredSkills.length
        }




        if (count > 0) {
            for (let i = 0; i < Math.min(count, filteredSkills.length); i++) {
                selectedSkills.push(this.skills[filteredSkills[i]]);
            }
        }


        return selectedSkills;
    }



    start() {
        this.randomSkill();
    }

    update(dt: number) {

    }
}


